package ua.com.fesvlast.hotel.model.connectionpool;

import java.sql.Connection;


public class ConnectionPool {
	
	private static ConnectionPool pool;
	private int maxConn=3;
	private Connection[] connArray=new Connection[maxConn];
	private int withdrewed=0;
	
	 ConnectionPool(){
		for(int i=0; i<maxConn; i++){
			connArray[i] =DBUtil.getConnection();
		}
	}

	static public ConnectionPool getConnPool(){
		ConnectionPool mcc;
		
		mcc=(pool==null? new ConnectionPool():pool);
		
		pool =mcc;
		return mcc;
	}
	
	synchronized public Connection getConnection(){
		Connection conn=null;
		
		while(withdrewed ==10){
			try {
				wait();
			} catch (InterruptedException e) { 
				System.err.println(e);
			}
		}
		withdrewed++;
		
		for(int i=0; i<maxConn; i++){
			if(connArray[i]!=null){
				conn =connArray[i];
				connArray[i]=null;
				break;
			}
		}
		
		notify();
		return conn;
	}
	
	synchronized public void releaseConnection(Connection conn){
		withdrewed--;
		
		/*try {
			conn.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		for(int i=0; i<maxConn; i++){
			if(connArray[i]==null){
				connArray[i] =conn;
				break;
			}
		}
		notify();
	}
	
	synchronized public void closeAll(){
		for (int i = 0; i<maxConn; i++){
			if (connArray[i] != null)
				try{
				//connArray[i].rollback();
				connArray[i].close();
				} catch (Exception e){
					System.err.println(e);
				}
			}
		connArray = null;
		}

}
